package com.robot.member.controller;

import com.robot.member.pojo.Consumption;
import com.robot.member.service.ConsumptionService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * consumption控制器层
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/consumption")
public class ConsumptionController {
    @Autowired
    private ConsumptionService consumptionService;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, consumptionService.findByIdAndMemberIdAndDeletedAtIsNull(id, claims.getId()));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map<String, String> searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        searchMap.put("memberId", claims.getId());
        Page<Consumption> pageList = consumptionService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageList.getTotalElements(), pageList.getContent()));
    }
}
